package org.beholder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.*;
import java.util.List;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.FileCleanerCleanup;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileCleaningTracker;

import org.apache.log4j.Logger;

/**
 * Designed retrieve image data sent as separate part within  Http
 * multi part POST request and store image in DB.
 */
public class MultipartUploadServlet extends AbstractServlet {
	
	private static final long serialVersionUID = 1L;

	private Logger logger = Logger.getLogger(MultipartUploadServlet.class);

    private ServletFileUpload upload;
    private DiskFileItemFactory factory;
    private FileCleaningTracker fileCleaningTracker;

    public void init() throws ServletException {

    	super.init();
    	    	
        // Create a factory for disk-based file items
        fileCleaningTracker = FileCleanerCleanup.getFileCleaningTracker(this.getServletContext());
        factory = new DiskFileItemFactory();
        factory.setRepository(new File("."));
        factory.setFileCleaningTracker(fileCleaningTracker);

        // Create a new file upload handler
        upload = new ServletFileUpload(factory);

    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sessionId = req.getSession().getId();
        try {
            @SuppressWarnings("unchecked")
			List<Object> items = upload.parseRequest(req);
            for (Object itemObj : items) {
                FileItem item = (FileItem) itemObj;
                if (!item.isFormField()) {
                    logger.debug("Not form field");
                    logger.debug("item.getName() = " + item.getName());
                    logger.debug("item.getFieldName() = " + item.getFieldName());
                    storeShot(item.getInputStream(), sessionId);
                } else {
                	logger.debug("Form field");
                }
            }
            resp.setStatus(HttpServletResponse.SC_OK);
            req.getRequestDispatcher("/upload.jsp").forward(req,resp);
        } catch (FileUploadException e) {
        	logger.error(e, e);
        }
    }

    private void storeShot(InputStream is, String sessionId) throws IOException {
        logger.debug("Upload bytes available:"+is.available());
        try {
            logger.info(is.available()+"bytes uploaded");
            PreparedStatement ps = conn.prepareStatement("INSERT INTO shots_tbl VALUES (NULL, ?, ?, ?)");
            ps.setString(1, sessionId);
            ps.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
            ps.setBinaryStream(3, is, is.available());
            int i = ps.executeUpdate();
            System.out.println(i + " records added");
        } catch (Exception e) {
        	logger.error(e, e);
        }
    }

}
